// pages/Comment/Comment.js
const Controller = require('../controllers/controllers').controller
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    animationData: {}, //弹出窗效果
    isShowPicker: true, //弹出窗显示
    loveIconId: '', //点击点赞爱心按钮
    inputBottom: 0, //用于输入框能键盘弹出使得布局上移
    content: '', //输入框内容,
    focusInput: false,
    rid: '', //关联id :评论的对象id
    type: 5, //1是栏目，2是合辑，3是音频，4是达人榜，5是评论
    bodyId: '', //表示评论的对象，具体是1是栏目，2是合辑，3是音频的id,当是一级评论则rid = bodyId
    audioDetail: {}, //音频，栏目，详情
    options: {}, //页面参数
    ReplyingPersonList: [], //评论回复信息
    pageNumber: 1,
    lastPage: false,
    totalRow: 0,
    toUserId: '',
    isCheckCollect: '', //检测点赞收藏返回来的id
    title:'评论'
  },
  timer: null,
  // 简介更多按钮
  moreBtn() {
    console.log('更多按钮')
    let _this = this;
    _this.setData({
      isShowPicker: false,
    })
    //创建动画
    var animation = wx.createAnimation({
      duration: 500, //动画的持续时间 默认400ms   数值越大，动画越慢   数值越小，动画越快
      timingFunction: 'linear', //动画的效果 默认值是linear
    })
    // 在当前页面添加animation属性 
    _this.animation = animation
    setTimeout(function () {
      _this.fadeIn(); //调用显示动画
    }, 20)

  },
  // 隐藏弹出窗
  cancleBtn() {
    let _this = this;
    var animation = wx.createAnimation({
      duration: 600, //动画的持续时间 默认400ms   数值越大，动画越慢   数值越小，动画越快
      timingFunction: 'linear', //动画的效果 默认值是linear
    })
    _this.animation = animation
    _this.fadeDown()
    //先执行下滑动画，再隐藏模块
    setTimeout(function () {
      _this.setData({
        isShowPicker: true,
        isShowSelect: true
      })
    }, 500)
  },
  //动画集
  fadeIn: function () {
    this.animation.translateY(0).step()
    this.setData({
      animationData: this.animation.export() //动画实例的export方法导出动画数据传递给组件的animation属性
    })
  },
  fadeDown: function () {
    this.animation.translateY(800).step()
    this.setData({
      animationData: this.animation.export(),
    })
  },
  // 点击输入框聚焦
  foucus(e) {
    var that = this;
    let type = ''
    let rid = ''
    console.log('e.detail.height', e, e.detail.height)
    // 判断是否为评论他人，否则是评论当前的其中一个（1是栏目，2是合辑，3是音频）
    console.log(this.data.focusInput)
    if (this.data.focusInput) {
      // 评论他人
      type = 5
    } else {
      // 评论（1是栏目，2是合辑，3是音频）
      type = this.data.options.type
      // 获取别的页面传来的参数
      rid = this.data.options.rid //音频或栏目等的id
      this.setData({
        rid
      })
    }
    that.setData({
      inputBottom: e.detail.height,
      type
    })

  },
  // 点击评论触发input的focus方法
  focusButn(e) {
    console.log('点击评论触发input的focus方法', e)
    this.setData({
      focusInput: true,
      rid: e.currentTarget.dataset.rid, //当前评论的id
      toUserId: e.currentTarget.dataset.touserid // 被评论人的id
    })
  },
  // 输入框失焦
  blur(e) {
    var that = this;
    that.setData({
      inputBottom: 0
    })
  },
  // 获取输入内容
  getInputText(e) {
    var that = this;
    // console.log(e)
    that.setData({
      content: e.detail.value
    })
  },
  // 输入框提交按钮
  submit() {
    var that = this;
    let content = this.data.content;
    let rid = this.data.rid;
    let type = this.data.type;
    console.log('输入框提交按钮', content, !Boolean(content))
    if (!Boolean(content)) {
      wx.showToast({
        title: '请输入内容',
        icon: 'none'
      })
      return
    }
    let params = {
      content,
      rid, //当前评论的id
      bodyId: that.data.options.rid,
      type, //评论对象的类型，1是栏目，2是合辑，3是音频，4是评论
      bodyType: that.data.options.type, //1是栏目，2是合辑，3是音频，4是达人榜
      toUserId: that.data.toUserId //用户id(指的是被评论者的id)
    }
    Controller.comment(params)
      .then(res => {
        console.log('评论发送', res)
        if (res.code == 0) {
          wx.showModal({
            title: '提示',
            content: '评论成功!',
            showCancel: false
          })
          this.setData({
            page:1,
            pageSize: 10,
            ReplyingPersonList:[],
            lastPage: false,
          })
          this.commentList()
      
          that.setData({
            content: '',
            focusInput: false,
            rid: this.data.options.rid,
            toUserId:''
          })
          app.updateScore(8)
        }
      })
  },
  // 点赞方法
  collectBtn(e) {
    console.log('点赞方法', e, this.data)
    let that = this;
    let ReplyingPersonList = this.data.ReplyingPersonList;
    let flag = null;
    ReplyingPersonList.map(item => {
      console.log(item.id, e.currentTarget.dataset.id)

      if (item.id == e.currentTarget.dataset.id) {
        item.select = item.select ? false : true
        flag = item.select ? false : true
        item.likeNums = flag ? item.likeNums - 1 : item.likeNums + 1
      }
    })
    that.setData({
      ReplyingPersonList
    })
    // 检测当前评论是否传回id
    that.checkCollect(e.currentTarget.dataset.id)
    console.log('flag', flag)
    if (that.timer) {
      clearTimeout(this.timer)
    }
    that.timer = setTimeout(() => {
      if (!flag) {
        that.collectfn(e)
      } else {
        that.delCollectfn(that.data.isCheckCollect, e)
      }

    }, 300)

  },
  // 检测是否点赞收藏
  checkCollect(rid) {
    Controller.checkCollect({
        type: 5,
        rid,
        token: wx.getStorageSync('logintoken')
      })
      .then(res => {
        console.log(res)
        if (res.code == 0) {
          this.setData({
            isCheckCollect: res.data.baseData
          })
        }
      })
  },
  // 点赞收藏方法
  collectfn(e) {
    let that = this;
    let params = {
      rid: e.currentTarget.dataset.id, //点赞的对象是评论，那rid就是对象的id
      bodyType: this.data.options.type,//（主体类型）
      bodyId: this.data.options.rid, //音频（或者栏目，合辑等）的id
      toUserId: e.currentTarget.dataset.touserid,
      type: 5
    }
    Controller.collect(params)
      .then(res => {
        console.log('点赞方法', res)
        app.updateScore(9)
        if (res.code == 0) {
          wx.showToast({
            title: res.msg,
            duration: 1000
          })
        }
      }).catch(err => {
        wx.showToast({
          title: err.data.msg,
          duration: 1000
        })
        return true
      })
    that.checkCollect(e.currentTarget.dataset.id)
  },
  // 取消收藏,点赞
  delCollectfn(ids, e) {
    let that = this;
    Controller.delCollect({
        ids
      })
      .then(res => {
        console.log('取消收藏', res)
        if (res.code == 0) {
          that.checkCollect(e.currentTarget.dataset.id)
        }
      })
  },

  // 评论回复人->评论列表 参数page pageSize rid（关联id） type=4
  commentList() {
    let that = this
    let params = {
      page: that.data.pageNumber,
      pageSize: 10,
      rid: this.data.options.rid, //关联id(音频的id)
      type: this.data.options.type, //评论对象的类型，1是栏目，2是合辑，3是音频，4是评论
      token: wx.getStorageSync('logintoken')
    }
    Controller.commentList(params)
      .then(res => {
        console.log('评论回复人', res)
        if (res.code == 0 && res.data && res.data.baseData && res.data.baseData.list) {
          res.data.baseData.list.map(item => {
            item.select = item.liked == 1 ? true : false;
            item.likeNums = item.likeCount
          })
          res.data.baseData.list.map(item => {
            item.createTime = app.getBeforeTime(item.createTime)
          })
          that.setData({
            ReplyingPersonList: that.data.ReplyingPersonList.concat(res.data.baseData.list),
            pageNumber: res.data.baseData.pageNumber,
            lastPage: res.data.baseData.lastPage,
            totalRow: res.data.baseData.totalRow,
          })
        }
      })
  },
  // 音频详情 -- 3
  audioDetail(audioId) {
    Controller.audioDetail({
        audioId,
        token: wx.getStorageSync('logintoken')
      })
      .then(res => {
        console.log('音频详情', res)
        if (res.code == 0) {
          this.setData({
            audioDetail: res.data
          })
        }
      })
  },
  // 合辑详情 -- 2
  compilationDetail(compilationId) {
    Controller.compilationDetail({
        compilationId,
        token: wx.getStorageSync('logintoken')
      })
      .then(res => {
        console.log('合辑详情', res)
        if (res.code == 0) {
          this.setData({
            audioDetail: res.data
          })
        }
      })
  },
  // 栏目详情 -- 1
  categoryDetail(categoryId) {
    Controller.categoryDetail({
        categoryId,
        token: wx.getStorageSync('logintoken')
      })
      .then(res => {
        console.log('栏目详情', res)
        if (res.code == 0) {
          this.setData({
            audioDetail: res.data
          })
        }
      })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    // 接收参数 音频的id（或者栏目，合辑等的id） 音频的（或者栏目，合辑等的type）type bodyId
    console.log('页面参数', options)
    
    //type  1是栏目，2是合辑，3是音频
    if (options.type == 1) {
      this.categoryDetail(options.rid);
    } else if (options.type == 2) {
      this.compilationDetail(options.rid);
    } else if (options.type == 3) {
      this.audioDetail(options.rid);
    }
    this.setData({
      bodyId: options.bodyId,
      options,
      rid: options.rid
    })

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    this.Dialog = this.selectComponent('#Dialog');
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.setData({
      ReplyingPersonList: []
    })
    this.commentList()
  },
  onHide() {
    clearTimeout(this.timer)
  },
  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    if (!this.data.lastPage) {
      this.setData({
        pageNumber: this.data.pageNumber + 1
      })
      this.commentList();
      console.log('页面上拉触底事件的处理函数')
    }
  },
  onShareAppMessage: function (e) {
    // if (e.from == "button") {
      let obj = {
        title: '有氧FM·评论',
        success: function (res) {
          
        },
        fail(err) {
          
        }
      }
      return obj
    // }
  },
  onShareTimeline: function (e) {
    // if (e.from == "button") {
      let obj = {
        title: '有氧FM·评论',
        success: function (res) {
          
        },
        fail(err) {
          
        }
      }
      return obj
    // }
  },
})